package com.xpsoft.app.user.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.xpsoft.app.user.UserLoginTypeConst;



/**
 * 安全过滤器
 * 
 * @Class Name SecurityFilter
 * @Author likang
 * @Create In Aug 20, 2010
 */
public class SecurityFilter implements Filter {
	
	private String loginPage;
	private String loginAction;
	
	public void destroy() {
		// TODO Auto-generated method stub

	}

	public void doFilter(ServletRequest servletRequest,
			ServletResponse servletResponse, FilterChain chain)
			throws IOException, ServletException {

		HttpServletRequest request = (HttpServletRequest) servletRequest;
		HttpServletResponse response = (HttpServletResponse) servletResponse;
		HttpSession session = ((HttpServletRequest) request).getSession();
		
		//System.out.println("in doFilter url:"+request.getRequestURI());
		//System.out.println("in doFilter session "+UserLoginTypeConst.USERINFO+":"+request.getSession().getAttribute(UserLoginTypeConst.USERINFO)) ;
		//System.out.println("in doFilter session CLIENT_PASS:"+request.getSession().getAttribute("CLIENT_PASS")) ;
		
		/**
		 * 解决 HTTP Referer头跨站脚本编制漏洞 begin
		 */
		//清理来自用户的所有输入，过滤 JavaScript 代码
		String referer = request.getHeader("referer");
		String pre = "<>\"'%;)(&+";
		StringBuffer sb = new StringBuffer();
		for(int i=0; referer!=null && i<referer.length(); i++) {
			 String temp = String.valueOf(referer.charAt(i));
			 //如果非法字符中包含该则过滤
			 if(!pre.contains(temp)) {
				sb.append(temp); 
			 }
		}
		request.setAttribute("backurl", sb.toString());
		/**
		 * 解决 HTTP Referer头跨站脚本编制漏洞 end
		 */
		
		
		//url资源
		String uri = request.getRequestURI();
		String contextPath = request.getContextPath();
		if (uri.contains(contextPath)) {
			uri = uri.substring(contextPath.length(), uri.length());
		}
		
		//如果首页或错误页面 允许通过 
		if (uri.startsWith(loginPage) || uri.startsWith(loginAction)){
			chain.doFilter(servletRequest, servletResponse);
		} else if(session.getAttribute(UserLoginTypeConst.USERINFO) != null){
			chain.doFilter(servletRequest, servletResponse);
		} else {
			response.sendRedirect(request.getContextPath() + "/"+loginPage);
		}
	}
	

	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub
		loginPage = "login.jsp";
		loginAction = "/user/loginUserAction";
	}

}
